﻿using System.Collections.Generic;

namespace BuzzX8.Xmpp.StreamElements.Factories
{
    public abstract class StreamElementFactory<TElement, TModel> :  StreamElementFactory where TElement : StreamElement
                                                                                         where TModel : class
    {
        private TModel defaultModel;

        public TModel DefaultModel
        {
            get { return defaultModel ?? (defaultModel = CreateModelByParameters(DefaultParameters)); }
        }

        public TElement Create(IDictionary<string, object> parameters = null)
        {
            return (TElement)CreateElement(parameters);
        }

        protected virtual TElement Create(PropertyDictionary parameters)
        {
            TModel elementModel = CreateModelByParameters(parameters);
            return Create(elementModel, parameters);
        }

        protected abstract TModel CreateModelByParameters(PropertyDictionary parameters);

        public TElement Create(TModel elementModel)
        {
            return Create(elementModel, new PropertyDictionary());
        }

        protected virtual TElement Create(TModel elementModel, PropertyDictionary parameters)
        {
            TElement element = CreateNewElement();
            UpdateElementByModel(element, elementModel);
            return element;
        }

        protected abstract TElement CreateNewElement();

        protected abstract void UpdateElementByModel(TElement element, TModel model);

        protected override StreamElement CreateElement(PropertyDictionary parameters)
        {
            return Create(parameters);
        }
    }
}
